const fs = require('fs');
const path = require('path');
const app = require('express').Router()

// 获取所有盘符接口
app.get('/driveLetters', (req, res) => {
  const driveLetters = global.driveLetters
  driveLetters.sort()
  res.json(driveLetters);
});

// 根据传入的地址，获取地址下的目录
app.post('/getDirectory', (req, res) => {
  const {
    fileType,
    getAll = false
  } = req.body
  let directoryPath = req.body.path;
  let types = []
  if (fileType) {
    fileType.split(',').forEach(i => {
      types.push(`.${i}`)
    })
  }
  // 读取目录内容
  fs.readdir(directoryPath, {
    withFileTypes: true
  }, (err, files) => {
    if (err) {
      console.error('无法读取目录:', err);
      res.status(500).json({
        error: '无法读取目录'
      });
      return;
    }
    let directory = []
    if (getAll) {
      files.forEach(file => {
        if (file.isDirectory()) {
          file.type = 'folder'
          file.fileExt = ''
          file.path = directoryPath
          directory.push(file)
        } else if (file.isFile()) {
          file.type = 'file'
          file.path = directoryPath
          file.fileExt = path.extname(file.name)
          directory.push(file)
        }
      })
    } else {
      if (fileType) {
        files.forEach(file => {
          if (file.isDirectory()) {
            file.type = 'folder'
            file.path = directoryPath
            file.fileExt = ''
            directory.push(file)
          } else if (types.indexOf(path.extname(file.name)) > -1) {
            file.type = 'file'
            file.path = directoryPath
            file.fileExt = '.' + fileType
            directory.push(file)
          }
        })
      } else {
        files.forEach(file => {
          if (file.isDirectory()) {
            file.type = 'folder'
            file.path = directoryPath
            file.fileExt = ''
            directory.push(file)
          }
        })
      }
    }
    res.json({
      directory
    });
  });
})

function getAllFiles(dirPath, suffix, fileList = []) {
  const files = fs.readdirSync(dirPath);

  files.forEach(file => {
    const filePath = path.join(dirPath, file);

    if (fs.statSync(filePath).isFile()) {
      // 判断文件扩展名是否为 .gltf
      if (path.extname(filePath).toLowerCase() === '.' + suffix) {
        fileList.push(filePath);
      }
    } else {
      // 如果是目录，则进行递归调用
      getAllFiles(filePath, suffix, fileList);
    }
  });

  return fileList;
}

// 根据传入的地址，获取地址下所有符合条件的文件（包括子目录下的）
app.post('/getAllFilesCor', (req, res) => {
  let {
    path,
    suffix
  } = req.body
  try {
    let fileList = getAllFiles(path, suffix)
    res.send({
      data: fileList,
      status: 200
    })
  } catch (error) {
    console.log(error)
    res.send(error)
  }
})

module.exports = app;